package com.pzh.mall.web.controller.quartz;


import cn.hehuoren.quartz.model.QuartzManager;
import cn.hehuoren.quartz.service.IQuartzManagerService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.pzh.sys.controller.BaseController;
import cn.hehuoren.core.utils.response.HttpResponseBody;
import cn.hehuoren.core.utils.ExceptionUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;


/**
 * 
 * @Title 
 * @Description 定时任务管理
 * @Copyright Copyright (c) 2015</p>
 * @Company 源本信息科技有限公司 Co., Ltd.</p>
 * @author ZhouMin
 * @version 1.0
 * @修改记录
 * @修改序号，修改日期，修改人，修改内容
 */
@SuppressWarnings("unchecked")
@RestController
@RequestMapping("/api/quartz")
public class QuartzManagerController extends BaseController {


    @Reference
    private IQuartzManagerService quartzManagerService;


    @RequestMapping(value = "/qryQuartzTask", method = RequestMethod.GET)
    public Object qryQuartzTask(HttpServletRequest request, QuartzManager quartzManager,
                                                  @RequestParam(required = false, defaultValue = "0") int page,
                                                  @RequestParam(required = false, defaultValue = "10") int rows, String sidx){
        return HttpResponseBody.successResponse("ok", quartzManagerService.selectQuartzManagerPage(quartzManager, page, rows,null));
    }


    /**
     * 保存定时任务
     * 
     * @param quartzManager
     * @param response
     * @return
     */
    @RequestMapping(value = "/saveQuartzTask", method = RequestMethod.POST)
    public HttpResponseBody saveQuartzTask(QuartzManager quartzManager, HttpServletResponse response,
                                         HttpServletRequest request){
        String[] paramKeys = request.getParameterValues("params[paramKey]");
        String[] paramValues = request.getParameterValues("params[paramValue]");
        try {
            if (paramKeys != null && paramKeys.length > 0) {
                for (int i = 0; i < paramKeys.length; i++ ) {
                    quartzManager.getJobDataMap().put(paramKeys[i].trim(), paramValues[i].trim());
                }
            }
            if(StringUtils.isEmpty(quartzManager.getDtlJobName())) {
                quartzManagerService.addQuarzTask(quartzManager);
            }else {
                quartzManagerService.updateQuarzTask(quartzManager);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            Map<String,String> resMap = ExceptionUtil.parseBusinessException(e);
            return new HttpResponseBody(resMap.get("code"),resMap.get("errorInfo"));
        }
        return HttpResponseBody.successResponse("success");
    }
   

    @GetMapping("getTaskDetail")
    public HttpResponseBody getTaskDetail(String dtlJobName, String dtlSchedName, String dtlJobGroup){
        QuartzManager quartzManager = quartzManagerService.getByKey(dtlSchedName, dtlJobName, dtlJobGroup);
        return HttpResponseBody.successResponse("ok", quartzManager);
    }

    /**
     * 定时任务操作
     * 
     * @param params paraArray
     */
    @RequestMapping(value = "/delWithQuarzTask", method = RequestMethod.POST)
    public HttpResponseBody delWithQuarzTask(String params, String operType) {
        QuartzManager quartzManager;
        String returnStr;
        boolean flag = true;
        if (StringUtils.isNotBlank(params)) {
            String[] paraArray = params.split("\\|");
            for (int i = 0; i < paraArray.length; i++ ) {
                quartzManager = new QuartzManager();
                quartzManager.setDtlJobName(paraArray[i].split(",")[0]);
                quartzManager.setDtlJobGroup(paraArray[i].split(",")[1]);
                try {
                    if (StringUtils.equals(operType, "delQuarzTask")) {
                        flag = quartzManagerService.deleteJob(quartzManager);
                    } else if (StringUtils.equals(operType, "pauseQuarzTask")) {
                        quartzManagerService.pauseJob(quartzManager);
                    } else if (StringUtils.equals(operType, "resumeQuarzTask")) {
                        quartzManagerService.resumeJob(quartzManager);
                    } else if (StringUtils.equals(operType, "interruptQuarzTask")) {
                        flag = quartzManagerService.interrupt(quartzManager);
                    } else if (StringUtils.equals(operType, "runQuarzTaskOnce")) {
                        quartzManagerService.triggerJob(quartzManager);
                    }
                } catch (Exception e) {
                    returnStr = "定时任务操作失败:" + e.getMessage();
                    logger.info(returnStr, e);
                    flag = false;
                }
            }
        } else {
            if (StringUtils.equals(operType, "pauseAllJob")) {// 暂停所有job
                quartzManagerService.pauseJob();
            } else if (StringUtils.equals(operType, "shutdownQuartz")) {// 停止调度器
                quartzManagerService.shutdownScheduler();
            }
        }
        if (flag) {
            return HttpResponseBody.successResponse("操作成功");
        } else {
            return HttpResponseBody.failResponse("操作失败");
        }
    }

    /**
     * job 参数转换
     * 
     * @param jobData
     * @return
     */
    private HashMap<String,String> formatJobData2Map(byte[] jobData) {
        if (null != jobData && jobData.length > 0) {
            InputStream inStream = new ByteArrayInputStream(jobData);
            Properties properties = new Properties();
            try {
                properties.load(inStream);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    inStream.close();
                } catch (Exception e) {
                    logger.error("转换JobDateMap异常：", e);
                }
            }
            return new HashMap<String,String>((Map)properties);
        }
        return null;
    }
}
